<?php

namespace app\common\logic;

use think\Db;

class CardLogic extends Logic
{
    static function cash_exchange($param = [])
    {
        $uid = $param['uid'];
        $scores = $param['scores'];
        if ($scores < 1) return ['code' => 0, 'msg' => '积分不能为空'];

        $my_scores = Db::name('user')->where('id', $uid)->value('scores');
        if ($my_scores < $scores) return ['code' => 0, 'msg' => '积分兑换超额'];

        Db::startTrans();

        $user_result = Db::name('user')->where('id', $uid)->update(['scores' => $my_scores - $scores]);

        $scores_result = Db::name('user_scoreslog')->insert([
            'uid' => $uid,
            'type' => 3,
            'affect_scores' => $scores,
            'account_scores' => $my_scores - $scores,
            'info' => '积分兑换',
            'add_time' => time(),
        ]);

        $card_result = Db::name('user_card')->insert([
            'uid' => $uid,
            'type' => 3,
            'title' => '积分兑换',
            'money' => number_format($scores / 100, 2, '.', ''),
            'status' => 2,
            'expired_time' => strtotime('+30 day'),
            'add_time' => time(),
        ]);

        if ($user_result && $scores_result && $card_result) {
            Db::commit();
            return ['code' => 1, 'msg' => '积分兑换成功'];
        } else {
            Db::rollback();
            return ['code' => 0, 'msg' => '积分兑换失败，请稍后重试'];
        }
    }

    static function send_card()
    {
        $activity_db = Db::name('activity');
        $order_db = Db::name('user_order');
        $card_db = Db::name('user_card');

        $list = $activity_db->where('status', 1)
            ->order('count asc')
            ->limit(0, 1)->select()->toArray();


        foreach ($list as $v) {
            $activity_db->where('id', $v['id'])->setInc('count');
            $activity_db->where('id', $v['id'])->update(['status' => 2]);

            $count = Db::name('user_card')->where([
                'activity_id' => $v['id'],
                'title' => $v['title'],
            ])->count();
            if ($count > 0) continue;

            $where = [];

            $data = $order_db->alias('o')->field('o.uid')
                ->join('tp_course c', 'c.id = o.course_id', 'left')
                ->where($where)->select()->toArray();

            $add_item = [];
            foreach ($data as $vv) {
                array_push($add_item, [
                    'uid' => $vv['uid'],
                    'type' => $v['platform'],
                    'title' => $v['title'],
                    'money' => $v['money'],
                    'expired_time' => $v['expired_time'],
                    'add_time' => $v['add_time'],
                ]);
            }

            if (count($add_item) > 0) $card_db->insertAll($add_item);
        }

    }
}